/**
 * @author Caius
 * @description
 * @version 1.0
 * @since Created in 2025-02-10
 */

package com.itsense.stock.utils;

import com.itsense.stock.pojo.domain.PermissionsSelectAllDomain;
import com.itsense.stock.pojo.entity.SysPermission;

import java.util.ArrayList;
import java.util.List;

public class PermissionUtil {
    /**
     * 获取子权限递归函数
     * @param parentId 父权限ID
     * @param allPermissions 所有权限
     * @return 子权限集合
     */
    public static List<PermissionsSelectAllDomain> getChildrenPermissions(String parentId,List<SysPermission> allPermissions) {
        // 初始化子权限列表
        List<PermissionsSelectAllDomain> children = new ArrayList<>();
        // 遍历所有权限，寻找父ID匹配的权限
        for (SysPermission permission : allPermissions) {
            // 如果当前权限Pid等于parentId，则将当前权限添加到子权限列表中
            if (permission.getPid().equals(parentId)) {
                PermissionsSelectAllDomain domain = new PermissionsSelectAllDomain();
                domain = domain.builder()
                        .id(String.valueOf(permission.getId()))
                        .title(permission.getTitle())
                        .icon(permission.getIcon())
                        .path(permission.getUrl())
                        .name(permission.getName())
                        .build();
                // 递归调用自己获取当前权限的子权限
                List<PermissionsSelectAllDomain> subChildren = getChildrenPermissions(permission.getId(),allPermissions);
                // 当前权限有子权限，则将子权限添加到当前权限中
                // 如果没有子权限，则创建一个空的子权限列表
                if (subChildren.size() > 0) {
                    domain.setChildren(subChildren);
                }else {
                    subChildren = new ArrayList<>();
                    domain.setChildren(subChildren);
                }
                // 将当前权限添加到父权限的子权限列表中
                children.add(domain);
            }
        }
        // 返回子权限列表
        return children;
    }
}
